/* 
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
Ext.chart.Chart.CHART_URL = '../../../ext3/resources/charts.swf';
Ext.QuickTips.init();
var _pageSize = 20;
var _title = '监测点月数据';
var store;
var now = new Date();
var loadServlet = '../../../servlet/data/YsjLoad';
var saveServlet = '../../../servlet/data/YsjSave';

var fieldNameE = ['reasonAnalyze', 'treatWay', 'completeCase', 'did'];
var fieldLabelE = ['原因分析', '处理', '完成情况'];

var theme = '月数据';

var columnsE = [
    {header: '原因分析', width: 80, sortable: true, dataIndex: 'reasonAnalyze'},
    {header: '处理', width: 80, sortable: true, dataIndex: 'treatWay'},
    {header: '完成情况', width: 80, sortable: true, dataIndex: 'completeCase'}
];

var tabs = new Ext.TabPanel({
    activeTab: 0,
    plain: true,
    enableTabScroll: true,
    defaults: {autoScroll: true},
    items: [{
            title: currentOrgName + '监测点月数据',
            id: 'main-tab',
            layout: "fit",
            tbar: new Ext.Toolbar([
                {
                    text: '每日电压',
                    iconCls: 'icon-daytime',
                    hidden: 'true',
                    handler: showVoltage31
                            , style: {marginLeft: '10px'}
                },
                {
                    text: '环比数据',
                    iconCls: 'icon-linkratio',
                    handler: compareRangeData
                },
                {
                    text: '合格率同比',
                    iconCls: 'icon-linkratio',
                    handler: compareSame
                },
                {
                    text: '合格率环比',
                    iconCls: 'icon-cycleratio',
                    handler: compareRange
                },
                {
                    text: '极值曲线',
                    iconCls: 'icon-curve',
                    handler: extremeLine
                },
                {
                    text: '原因处理',
                    iconCls: 'icon-linkratio',
                    handler: reasonHandle
                }
            ]),
            listeners: {
                'render': function() {
                    tbarPoint.render(this.tbar);
                }
            }
        }
    ]
});



var inputForm = new Ext.FormPanel(
        {
            xtype: 'form',
            id: 'input-form',
            bodyStyle: 'padding:15px;background:transparent',
            frame: true,
            border: false,
            url: saveServlet,
            items: [
                {
                    xtype: 'textfield',
                    fieldLabel: '原因分析',
                    name: 'reasonAnalyze',
                    anchor: '95%'
                },
                {
                    xtype: 'textfield',
                    fieldLabel: '处理',
                    name: 'treatWay',
                    anchor: '95%'
                },
                {
                    xtype: 'textfield',
                    fieldLabel: '完成情况',
                    name: 'completeCase',
                    anchor: '95%'
                }
            ],
            buttons: [{
                    text: '保存',
                    iconCls: 'icon-save',
                    handler: function() {
                        var submitConfig = {
                            success: function(form, action) {
                                store.reload();
                                win.hide();
                            },
                            failure: function(form, action) {
                                switch (action.failureType) {
                                    case Ext.form.Action.CONNECT_FAILURE:
                                        Ext.Msg.alert('提示', '网络连接失败');
                                        break;
                                    case Ext.form.Action.SERVER_INVALID:
                                        Ext.Msg.alert('提示', action.result.msg);
                                }
                            },
                            params: {}
                        };
                        var token1 = new Date().getTime();
                        submitConfig.params.token = token;
                        submitConfig.params.token1 = token1;
                        submitConfig.params.id = checkboxSel.getSelected().get('did');
                        //alart(did);
                        submitConfig.params.cmd = 'reason';
                        Ext.getCmp('input-form').getForm().submit(submitConfig);
                    }
                }, {
                    text: '取消',
                    handler: function() {
                        win.hide();
                    }
                }]
        }
);

var win = new Ext.Window({
    layout: 'form',
    width: 680,
    autoHeight: true,
    closeAction: 'hide',
    items: [inputForm]
});

function reasonHandle() {
    updated = true;
    if (checkboxSel.getSelections().length === 0) {
        Ext.Msg.alert("提示", "您还没有选择，需要选择一个记录才能修改");
    }
    else if (checkboxSel.getSelections().length > 1) {
        Ext.Msg.alert("提示", "您选择了多个记录，只能选择一个记录进行修改");
    }
    else {

        var rec = checkboxSel.getSelected();
        var date = rec.get("date");
        //alert(date);
        if (date === null || date === '') {
            Ext.Msg.alert("系统提示", "该监测点本日无数据");
            return;
        }

        if (win === null) {
            win = new Ext.Window({
                layout: 'form',
                width: 340,
                autoHeight: true,
                closeAction: 'hide',
                modal: true,
                items: [inputForm]
            });
        }
        type = 2;
        Ext.getCmp('input-form').getForm().loadRecord(checkboxSel.getSelected());
        win.setTitle('原因处理' + theme);
        win.show();
    }
}


var hourSeries = [
    {
        yField: 'voltage',
        displayName: '电压值',
        style: {
            fillColor: 0xAAAAFF,
            borderColor: 0x3333FF,
            lineColor: 0x3333FF
        }
    }
];
var extraStyle = {
    xAxis: {
        majorGridLines: {color: 0x999999, size: 1}
    },
    yAxis: {
        titleRotation: -90
    },
    legend: {
        display: "right",
        padding: 5,
        spacing: 2,
        font: {color: 0x000000, family: "Arial", size: 12},
        border: {size: 1, color: 0x999999}
    }

};
function showVoltage31() {
    var r = checkboxSel.getSelected();
    if (!r.get('dataYear')) {
        Ext.Msg.alert("系统提示", "该日无数据");
        return;
    }
    if (checkboxSel.getSelections().length === 0) {
        Ext.Msg.alert("系统提示", "您还没有选择监测点");
        return;
    } else if (checkboxSel.getSelections().length > 1) {
        Ext.Msg.alert("系统提示", "只能选择一个记录");
        return;
    }
    var record = checkboxSel.getSelected();
    //alert(record.get('name'));
    var vid = record.get("dataYear") + '年' + record.get("dataMonth") + '月' + record.get('dataDay') + "日" + record.get('name');
    var hoursData = new Array();
    for (var i = 0; i < 24; i++) {
        var fieldName = '';
        if (i < 10)
            fieldName = "h0" + i;
        else
            fieldName = "h" + i;
        var voltage = parseFloat(record.get(fieldName));
        hoursData[i] = [i, voltage];
    }
    var hoursStore = new Ext.data.ArrayStore({
        autoDestroy: false,
        fields: ['hour', 'voltage']
    });
    hoursStore.loadData(hoursData);
    var chartPanel = new Ext.Panel({
        //title: 'Movie Rentals',
        //renderTo: Ext.getBody(),
        //width: 500,
        //height: 300,
        layout: 'fit',
        items: {
            xtype: 'columnchart',
            store: hoursStore,
            series: hourSeries,
            xField: 'hour',
            yField: 'volatage',
            extraStyle: extraStyle,
            yAxis: new Ext.chart.NumericAxis({
                displayName: 'Rentals',
                labelRenderer: Ext.util.Format.numberRenderer('0,0'),
                title: '电压值'
            }),
            xAxis: new Ext.chart.CategoryAxis({
                title: '小时'
            })
        }
    });
    var tab = tabs.add({
        title: vid,
        closable: true,
        id: vid,
        layout: 'fit'
                , items: [chartPanel]
    });
    //tab.add(chartPanel);
    //Ext.getCmp(vid).add(chartPanel);
    //alert('cde');
    tab.show();
}


function compareRangeData() {
    var record = checkboxSel.getSelected();
    if (checkboxSel.getSelections().length === 0) {
        Ext.Msg.alert("系统提示", "您还没有选择监测点");
        return;
    } else if (checkboxSel.getSelections().length > 1) {
        Ext.Msg.alert("系统提示", "只能选择一个记录");
        return;
    }
    var vid = record.get('name') + ' 月数据';
    var pointId = record.get('id');

    var ysjRangeDataStore = new Ext.data.JsonStore({
        url: loadServlet,
        root: 'data',
        idProperty: 'date',
        totalProperty: 'count',
        fields: fieldName,
        autoLoad: true,
        baseParams: {lock:lock,cmd: 'rangeData', pointId: pointId, start: 0, limit: _pageSize, dateFrom: now.add(Date.MONTH, -12).format('Ym'), dateTo: now.format('Ym')}
    });

    var gridRangeData = new Ext.grid.GridPanel({
        store: ysjRangeDataStore,
        columns: columns,
        loadMask: true,
        bbar: new Ext.PagingToolbar({
            pageSize: _pageSize,
            store: ysjRangeDataStore,
            displayInfo: true,
            displayMsg: '显示记录：{0} - {1}   总记录：{2}',
            emptyMsg: '目前没有信息'
        })
    });
    var tab = tabs.add({
        title: vid,
        closable: true,
        id: vid,
        layout: 'fit',
        tbar: [
            {
                text: "选择开始日期:", xtype: 'label', style: {marginLeft: '20px'}
            },
            {
                xtype: 'datefield',
                id: 'DayFromRangeData' + pointId,
                value: now.add(Date.MONTH, -12),
                format: 'Y年m月',
                width: 150,
                listeners: {
                    select: function(c, date) {
                        var dayFrom = c.getValue();
                        ysjRangeDataStore.baseParams.dayFrom = dayFrom.format('Ym');
                    }
                }
            },
            '-',
            {
                text: "选择结束日期:", xtype: 'label', style: {marginLeft: '20px'}
            },
            {
                xtype: 'datefield',
                id: 'DayToRangeData' + pointId,
                format: 'Y年m月',
                value: now,
                width: 150,
                listeners: {
                    select: function(c, date) {
                        var dayTo = c.getValue();
                        ysjRangeDataStore.baseParams.dayTo = dayTo.format('Ym');
                    }
                }
            },
            {
                xtype: 'button',
                text: '搜索',
                iconCls: 'icon-search',
                width: 60,
                style: {marginLeft: '20px'},
                handler: function() {
                    ysjRangeDataStore.reload();
                }
            }
        ]
    });
    Ext.getCmp(vid).add(gridRangeData);
    tab.show();
}

function compareSame() {
    var record = checkboxSel.getSelected();
    if (checkboxSel.getSelections().length === 0) {
        Ext.Msg.alert("系统提示", "您还没有选择监测点");
        return;
    } else if (checkboxSel.getSelections().length > 1) {
        Ext.Msg.alert("系统提示", "只能选择一个记录");
        return;
    }
    var vid = record.get('name') + ' 日合格率同比曲线';
    var pointId = record.get('id');

    var tipRenderer = function(chart, rec, index, series) {
        var yearInfo = '月份: ' + rec.get('date');
        var empInfo = '合格率' + ': '
                + rec.get('rate');
        return yearInfo + '\n' + empInfo;
    };
    var extraStyle = {
        xAxis: {
            majorGridLines: {
                color: 0x999999,
                size: 1
            }
        },
        yAxis: {
            titleRotation: -90
        },
        legend: {
            display: 'bottom',
            padding: 5,
            spacing: 2,
            font: {color: 0x000000, family: 'Arial', size: 12},
            border: {size: 1, color: 0x999999}
        }
    };
    var series = [
        {
            yField: 'lastRate',
            displayName: '去年',
            style: {
                fillColor: 0xAAAAFF,
                borderColor: 0x3333FF,
                lineColor: 0x3333FF
            }
        },
        {
            yField: 'rate',
            displayName: '今年',
            style: {
                fillColor: 0xAAFFAA,
                borderColor: 0x33AA33,
                lineColor: 0x33AA33
            }
        }
    ];
    var YsjSameStore = new Ext.data.JsonStore({
        url: loadServlet,
        root: 'data',
        idProperty: 'date',
        totalProperty: 'count',
        autoLoad: true,
        fields: ['date', 'rate', 'lastRate'],
        baseParams: {lock:lock,cmd: "same", dayFrom: now.add(Date.MONTH, -12).format('Y-m'), dayTo: now.format('Y-m-d'), pointId: record.get('id')}
    });
    var dayFrom;
    var dayTo;

    var chartPanel = {
        xtype: 'columnchart',
        store: YsjSameStore,
        xField: 'date',
        tipRenderer: tipRenderer,
        //yField: 'rate',
        series: series,
        extraStyle: extraStyle,
        xAxis: new Ext.chart.CategoryAxis({
            displayName: '月份',
            title: '月份'
        }),
        yAxis: new Ext.chart.NumericAxis({
            displayName: '电压合格率',
            title: '电压合格率',
            labelRenderer: Ext.util.Format.
                    numberRenderer('0,0.000')
        })
    };

    var tab = tabs.add({
        title: vid,        
        closable: true,
        id: vid,
        layout: 'fit'
    });
    //tab.add(chartPanel);
    Ext.getCmp(vid).add(chartPanel);
    //alert('cde');
    tab.show();
}

function compareRange() {
    var record = checkboxSel.getSelected();

    if (checkboxSel.getSelections().length === 0) {
        Ext.Msg.alert("系统提示", "您还没有选择监测点");
        return;
    } else if (checkboxSel.getSelections().length > 1) {
        Ext.Msg.alert("系统提示", "只能选择一个记录");
        return;
    }
    var pointId = record.get('id');
    var vid = record.get('name') + ' 月合格率曲线';

    var tipRenderer = function(chart, rec, index, series) {
        var yearInfo = '日期: ' + rec.get('dataDate');
        var empInfo = '合格率' + ': '
                + rec.get('rate');
        return yearInfo + '\n' + empInfo;
    };
    var extraStyle = {
        xAxis: {
            majorGridLines: {
                color: 0x999999,
                size: 1
            }
        },
        yAxis: {
            titleRotation: -90
        }
    };
    var YsjRateStore = new Ext.data.JsonStore({
        url: loadServlet,
        root: 'data',
        idProperty: 'dataDate',
        totalProperty: 'count',
        autoLoad: true,
        fields: ['dataDate', 'rate'],
        baseParams: {cmd: "range", dayFrom: now.add(Date.MONTH, -12).format('Ym'), dayTo: now.format('Ym'), pointId: record.get("id")}
    });
    var dayFrom;
    var dayTo;
    var chartPanel = {
        xtype: 'linechart',
        store: YsjRateStore,
        xField: 'dataDate',
        tipRenderer: tipRenderer,
        yField: 'rate',
        extraStyle: extraStyle,
        xAxis: new Ext.chart.CategoryAxis({
            displayName: '日期',
            title: '日期'
        }),
        yAxis: new Ext.chart.NumericAxis({
            displayName: '电压合格率',
            title: '电压合格率',
            labelRenderer: Ext.util.Format.
                    numberRenderer('0,0.000')
        })
    };

    var tab = tabs.add({
        title: vid,
        //iconCls: 'icon-tab',
        //bodyStyle: 'padding: 5px',
        //html:'abc',
        tbar: [
            {
                text: "选择开始日期:", xtype: 'label', style: {marginLeft: '20px'}
            },
            {
                xtype: 'datefield',
                id: 'DayFromRate' + pointId,
                value: now.add(Date.DAY, -30),
                format: 'Y年m月d日',
                width: 150,
                listeners: {
                    select: function(c, date) {
                        dayFrom = c.getValue();
                        YsjRateStore.baseParams.dayFrom = dayFrom.format('Y-m-d');
                    }
                }
            },
            '-',
            {
                text: "选择结束日期:", xtype: 'label', style: {marginLeft: '20px'}
            },
            {
                xtype: 'datefield',
                id: 'DayToRate' + pointId,
                format: 'Y年m月d日',
                value: now,
                width: 150,
                listeners: {
                    select: function(c, date) {
                        dayTo = c.getValue();
                        YsjRateStore.baseParams.dayTo = dayTo.format('Y-m-d');
                    }
                }
            },
            {
                xtype: 'button',
                text: '搜索',
                iconCls: 'icon-search',
                width: 60,
                style: {marginLeft: '20px'},
                handler: function() {
                    YsjRateStore.baseParams.pointId = record.get("id");
                    YsjRateStore.baseParams.dayFrom = Ext.getCmp("DayFromRate" + pointId).getValue().format('Y-m-d');
                    YsjRateStore.baseParams.dayTo = Ext.getCmp('DayToRate' + pointId).getValue().format('Y-m-d');
                    YsjRateStore.load({params: {cmd: "range"}});
                }
            }],
        closable: true,
        id: vid,
        layout: 'fit'
    });
    //tab.add(chartPanel);
    Ext.getCmp(vid).add(chartPanel);
    //alert('cde');
    tab.show();
}

function extremeLine() {
    var record = checkboxSel.getSelected();

    if (checkboxSel.getSelections().length === 0) {
        Ext.Msg.alert("系统提示", "您还没有选择监测点");
        return;
    } else if (checkboxSel.getSelections().length > 1) {
        Ext.Msg.alert("系统提示", "只能选择一个记录");
        return;
    }
    var vid = record.get('name') + ' 月极值曲线';

    //当前年每月合格率走势
    //var loadServlet = '../../servlet/voltagedata/YsjLoad';

    var tipRenderer = function(chart, rec, index, series) {
        var yearInfo = '日期: ' + rec.get('date');
        var empInfo = series.displayName + ': '
                + rec.get(series.yField);
        return yearInfo + '\n' + empInfo;
    };
    var extraStyle = {
        xAxis: {
            majorGridLines: {
                color: 0x999999,
                size: 1
            }
        },
        yAxis: {
            titleRotation: -90
        },
        legend: {
            display: 'bottom',
            padding: 5,
            spacing: 2,
            font: {color: 0x000000, family: 'Arial', size: 12},
            border: {size: 1, color: 0x999999}
        }
    };
    var series = [
        {
            yField: 'lowerLimit',
            displayName: '电压下限值',
            style: {
                fillColor: 0xFF0000,
                borderColor: 0xFF0000,
                lineColor: 0xFF0000,
                lineSize: 1
            }
        }, {
            yField: 'upperLimit',
            displayName: '电压上限值',
            style: {
                fillColor: 0xFF0000,
                borderColor: 0xFF0000,
                lineColor: 0xFF0000,
                lineSize: 1
            }
        },
        {
            yField: 'maxVoltage',
            displayName: '电压最大值',
            style: {
                fillColor: 0xFFAAAA,
                borderColor: 0xAA3333,
                lineColor: 0xAA3333
            }
        },
        {
            yField: 'minVoltage',
            displayName: '电压最小值',
            style: {
                fillColor: 0xAAAAFF,
                borderColor: 0x3333FF,
                lineColor: 0x3333FF
            }
        },
        {
            type: 'line',
            yField: 'avgVoltage',
            displayName: '电压平均值',
            style: {
                fillColor: 0xAAFFAA,
                borderColor: 0x33AA33,
                lineColor: 0x33AA33
            }
        }
    ];
    var YsjExtremeStore = new Ext.data.JsonStore({
        url: loadServlet,
        root: 'data',
        idProperty: 'date',
        totalProperty: 'count',
        autoLoad: true,
        fields: ['id', 'date','dateStr', 'lowerLimit', 'upperLimit', 'maxVoltage', 'minVoltage', 'avgVoltage'],
        baseParams: {lock:lock,cmd: "extreme", dateFrom: now.add(Date.MONTH, -12).format('Ym'), dateTo: now.format('Ym'), pointId: record.get('id')}
    });
    /*YsjExtremeStore.on('load', function(s, records, options) {
        for (var i = 0; i < records.length; i++) {
            var r = records[i];
            r.set('lowerlimit', 600);
            r.set('upperlimit', 1030);
        }
    });*/
    var dayFrom;
    var dayTo;
    var chartPanel = {
        xtype: 'linechart',
        store: YsjExtremeStore,
        xField: 'date',
        tipRenderer: tipRenderer,
        //yField: 'maxVoltage',
        extraStyle: extraStyle,
        series: series,
        xAxis: new Ext.chart.CategoryAxis({
            displayName: '月',
            title: '日期'
        }),
        yAxis: new Ext.chart.NumericAxis({
            displayName: '电压',
            title: '电压值',
            labelRenderer: Ext.util.Format.
                    numberRenderer('0,0.000')
        })
    };

    var tab = tabs.add({
        title: vid,
        //iconCls: 'icon-tab',
        //bodyStyle: 'padding: 5px',
        //html:'abc',
        tbar: [
            {
                text: "选择开始日期:", xtype: 'label', style: {marginLeft: '20px'}
            },
            {
                xtype: 'datefield',                
                value: now.add(Date.MONTH, -1),
                format: 'Y年m月',
                width: 150,
                listeners: {
                    select: function(c, date) {
                        dayFrom = c.getValue();
                        YsjExtremeStore.baseParams.dateFrom = dayFrom.format('Ym');
                    }
                }
            },
            '-',
            {
                text: "选择结束日期:", xtype: 'label', style: {marginLeft: '20px'}
            },
            {
                xtype: 'datefield',                
                format: 'Y年m月',
                value: now,
                width: 150,
                listeners: {
                    select: function(c, date) {
                        dayTo = c.getValue();
                        YsjExtremeStore.baseParams.dateTo = dayTo.format('Ym');
                    }
                }
            },
            {
                xtype: 'button',
                text: '搜索',
                iconCls: 'icon-search',
                width: 60,
                style: {marginLeft: '20px'},
                handler: function() {
                    YsjExtremeStore.baseParams.pointId = record.get("id");                    
                    
                    YsjExtremeStore.load({params: {cmd: "extreme"}});
                }
            }
        ],
        closable: true,
        id: vid,
        layout: 'fit'
    });
    //tab.add(chartPanel);
    Ext.getCmp(vid).add(chartPanel);
    tab.show();

}

function downloadExcel() {
    store.baseParams.type = 24;
    var encodeParams = Ext.urlEncode(store.baseParams);
    open('../../../servlet/common/ExcelFileCreate?' + encodeParams);
}

var checkboxSel = new Ext.grid.CheckboxSelectionModel();
var store;
function buildWindow() {
    store = new Ext.data.JsonStore({
        url: loadServlet,
        root: 'data',
        idProperty: 'id',
        totalProperty: 'count',
        fields: fieldName.concat(fieldNameE),
        autoLoad: true,
        baseParams: {lock:lock,cmd: 'general', start: 0, limit: _pageSize, dateFrom: now.format('Ym'), dateTo: now.format('Ym')}
    });

    tbarPoint.insert(0, {
        xtype: 'datefield',
        id: 'dateFrom',
        format: 'Y年m月',
        width: 150,
        value: now,
        listeners: {
            select: function(c, date) {                ;
                store.baseParams.dateFrom =  date.format('Ym');
                store.baseParams.dateTo = date.format('Ym');
            }
        }
    }
    );
    tbarPoint.add(
            {
                xtype: 'button',
                text: '导出',
                iconCls: 'icon-excel',
                width: 60,
                handler: downloadExcel
            });

    var grid = new Ext.grid.GridPanel({
        //title: _title,
        store: store,
        sm: checkboxSel,
        columns: [checkboxSel].concat(columns).concat(columnsE),
        loadMask: true,
        bbar: new Ext.PagingToolbar({
            pageSize: _pageSize,
            store: store,
            displayInfo: true,
            displayMsg: '显示记录：{0} - {1}   总记录：{2}',
            emptyMsg: '目前没有信息'
        })
    });
    Ext.getCmp('main-tab').add(grid);
    var applicationUI = new Ext.Viewport({
        layout: "fit",
        items: [
            tabs
        ]
    });
}
Ext.onReady(buildWindow);
